package cn.zhaopin.starter.security.handler;

import cn.zhaopin.starter.security.basic.UserContext;
import cn.zhaopin.starter.security.cache.SecurityCacheUtil;
import cn.zhaopin.starter.security.common.JWTUtils;
import cn.zhaopin.starter.security.common.SecurityConstant;
import cn.zhaopin.starter.security.properties.JwtProperties;
import com.google.common.base.Splitter;
import lombok.SneakyThrows;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.WebFilterChainServerAuthenticationSuccessHandler;
import org.springframework.util.CollectionUtils;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * Description: 登陆成功handler
 *
 * @author zuomin (myleszelic@outlook.com)
 * @date: 2021/09/29-09:37
 */
public class BasicServerAuthenticationSuccessHandler extends WebFilterChainServerAuthenticationSuccessHandler {

    private final JwtProperties jwtProperties;

    private final SecurityCacheUtil securityCacheUtil;

    public BasicServerAuthenticationSuccessHandler(JwtProperties jwtProperties, SecurityCacheUtil securityCacheUtil) {
        this.jwtProperties = jwtProperties;
        this.securityCacheUtil = securityCacheUtil;
    }

    @Override
    public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
        ServerHttpResponse response = webFilterExchange.getExchange().getResponse();
        HttpHeaders headers = response.getHeaders();
        headers.set("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        headers.set("Cache-Control", "no-store,no-cache,must-revalidate,max-age-8");

        UserContext userContext = (UserContext) authentication.getPrincipal();

        String token = getCacheOrCreateToken(userContext);

        String successResult = String.format(SecurityConstant.LOGIN_SUCCESS, token, DateUtils.addSeconds(new Date(), jwtProperties.getValidateInSecond()).getTime());

        return response.writeWith(Mono.just(response.bufferFactory().wrap(successResult.getBytes(StandardCharsets.UTF_8))));
    }

    /**
     * 沿用已经存在的token, 不存在,创建一个新的token
     * @param userContext
     * @return
     */
    @SuppressWarnings("UnstableApiUsage")
    private String getCacheOrCreateToken(UserContext userContext) {
        //todo 非阻塞redis 从缓存中获取token
        String tokenKeyPattern = JWTUtils.getTokenCacheKey(userContext.getId().toString(), "*");
        Set<String> tokenKeys = securityCacheUtil.keys(tokenKeyPattern);
        if (!CollectionUtils.isEmpty(tokenKeys)) {
            // 只获取第一个即可
            String firstTokenKey = tokenKeys.iterator().next();

            List<String> keySplit = Splitter.on(":").splitToList(firstTokenKey);
            return keySplit.get(keySplit.size() - 1);
        }
        else {
            String token = JWTUtils.createJavaWebToken4JwtAuth(userContext.getId().toString(), jwtProperties.getSecretKey(), jwtProperties.getValidateInSecond());
            // 保存token cache
            saveTokenCache(userContext, token, jwtProperties.getValidateInSecond());

            return token;
        }
    }

    /**
     * 保存token缓存
     * @param userContext user
     * @param token token
     * @param expireInSecond expire
     */
    @SneakyThrows
    private void saveTokenCache(UserContext userContext, String token, Integer expireInSecond) {
        String tokenCacheKey = JWTUtils.getTokenCacheKey(userContext.getId().toString(), token);
        securityCacheUtil.set(tokenCacheKey, userContext, expireInSecond);
    }

    /**
     * 构建jwt内容
     * @param userContext user
     * @return
     */
    private Map<String, Object> buildClaims(UserContext userContext) {
        Map<String, Object> tokenClaims = new HashMap<>(1 << 2);
        tokenClaims.put(SecurityConstant.CLAIM.X_UID, userContext.getId());
        return tokenClaims;
    }
}
